package net.sx.minemodule.mvp.activities;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.util.OSSManager;
import com.kedll.library.util.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import net.sx.minemodule.MineApiUtils;
import net.sx.minemodule.R;
import net.sx.minemodule.adapter.GridImageAdapter;
import net.sx.minemodule.databinding.MineActivityFeedbackBinding;
import net.sx.minemodule.mvp.bean.FeedBackParams;
import net.sx.minemodule.mvp.presenters.MineFeedbackUploadPresenter;
import net.sx.minemodule.widget.FullyGridLayoutManager;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 意见反馈
 */
//@RuntimePermissions
@Route(path = ARouterPath.PATH_MINE_FEEDBACK)
public class FeedbackActivity extends MyBaseFragmentActivity<MineActivityFeedbackBinding, MineFeedbackUploadPresenter>/* implements RadioGroup.OnCheckedChangeListener */ {
    private PopupWindow pop;
    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNum = 3;
    private RecyclerView mRecyclerView; //展示图片的控件
//    private StringBuilder sb;   //把选择的type拼接起来

    private RadioButton productPos, viewPos, operatingPos, propose, errorPos, otherPos;    //依次是商品问题，界面问题，操作问题，优化建议，卡顿报错，其他问题
    private RadioGroup typeItem1, typeItem2;    //类型选择
    private int type = 0;   //类型id (1=商品问题，2=界面问题，3操作问题，4=优化建议，5=闪退/报错，6=其他问题)

    //    private List<String> checkBoxString;   //checkbox 的集合
    private EditText infoEdit;  //输入反馈内容控件
    private EditText phone;
    private Button btnSubmit;   //提交按钮

    private List<String> filePath;      //本地图片路径集合
    private static List<String> OSSFilePath;   //截取后需要上传到服务器的路径集合


    @Override
    protected MineFeedbackUploadPresenter getPresenter() {
        return new MineFeedbackUploadPresenter(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.mine_activity_feedback;
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);
        setTitle("意见反馈");
    }

    @Override
    protected void initEvent() {
        //TODO
        mRecyclerView = mBinding.feedbackUpload.recycler;
        btnSubmit = mBinding.btnSubmit;
        phone = mBinding.feedbackTelephone.findViewById(R.id.telephone);

        initFeedbackType();
        initWidget();
//        FeedbackActivityPermissionsDispatcher.showPopWithPermissionCheck(this);

        infoEdit = mBinding.feedbackInfo.findViewById(R.id.info_edit);

        btnSubmit.setOnClickListener(v -> {
            if (mPresenter.submitCheck(type, infoEdit.getText().toString(), phone.getText().toString())) {   //过滤是否满足条件
                FeedBackParams params = new FeedBackParams();
                params.setTypeId(type);
                params.setContent(infoEdit.getText().toString());
                params.setPhone(phone.getText().toString());

                if (filePath != null) { //过滤是否有上传图片
//                    new Thread(() -> {    //此处应该是需要开一个子线程，通过handle把数据传出去
                    for (int i = 0; i < filePath.size(); i++) {
                        String s = OSSManager.uploadImage(filePath.get(i));
                        String mall = s.substring(s.indexOf("mall"));   //截取mall后面的字符串
                        Log.d(TAG, "initEvent: mall == " + mall);
                        OSSFilePath.add(mall);  //此处有bug，重新选择照片后，会累计添加到这个集合中
                    }
//                    }).start();
                }
                params.setImgFiles(OSSFilePath);    //把截取后的图片设置进参数bean中
                Log.d(TAG, "initEvent: params == " + JSON.toJSONString(params));
                MineApiUtils.feedBackSave(params, s -> {    //调用提交反馈接口
                    ToastUtil.showToast(s); //提示用户提交结果
                    new Handler().postDelayed(FeedbackActivity.this::finish, 2000); //延迟2秒关闭提交页面
                }, throwable -> {
                });
            }

        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    /**
     * 初始化反馈类型CheckBox控件
     */
    private void initFeedbackType() {

        typeItem1 = mBinding.typeItem1;
        typeItem2 = mBinding.typeItem2;
        productPos = mBinding.productPosition;
        viewPos = mBinding.viewPosition;
        operatingPos = mBinding.operatingPosition;
        propose = mBinding.propose;
        errorPos = mBinding.errorPosition;
        otherPos = mBinding.otherPosition;

        typeItem1.setOnCheckedChangeListener(new MyRadioGroupOneListener());
        typeItem2.setOnCheckedChangeListener(new MyRadioGroupTwoListener());
    }

    /*@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        FeedbackActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }*/

    /**
     * 初始化从图库、相机中获取图片展示控件
     */
    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((position, v) -> {
            if (selectList.size() > 0) {
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片 可自定长按保存路径
                        //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                        PictureSelector.create(FeedbackActivity.this).externalPicturePreview(position, selectList);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(FeedbackActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(FeedbackActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        });
    }

//    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})

    /**
     * 从图库、相机中获取图片弹框
     */
    public void showPop() {
        View bottomView = View.inflate(this, R.layout.le_select_layout, null);
        TextView mAlbum = bottomView.findViewById(R.id.galleryBtn);
        TextView mCamera = bottomView.findViewById(R.id.photoBtn);
        TextView mCancel = bottomView.findViewById(R.id.cancelBtn);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = getWindow().getAttributes();
            lp1.alpha = 1f;
            getWindow().setAttributes(lp1);
        });
        pop.setAnimationStyle(R.style.mine_main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = view -> {
            int i = view.getId();
            if (i == R.id.galleryBtn) {//相册
                PictureSelector.create(FeedbackActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(maxSelectNum)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);

            } else if (i == R.id.photoBtn) {//拍照
                PictureSelector.create(FeedbackActivity.this)
                        .openCamera(PictureMimeType.ofImage())
                        .forResult(PictureConfig.CHOOSE_REQUEST);

            } else if (i == R.id.cancelBtn) {//取消
                //closePopupWindow();
            }
            closePopupWindow();
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    /**
     * 关闭下拉弹框
     */
    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    /**
     * 添加图片时的点击事件
     */
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = this::showPop;

    /**
     * 选择图片回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        filePath = new ArrayList<>();
        OSSFilePath = new ArrayList<>();
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (int i = 0; i < images.size(); i++) {
                        LocalMedia media = images.get(i);
                        Log.d(TAG, "onActivityResult: media.getPath() === " + media.getPath());
                        String imgUrl = media.getPath();
                        filePath.add(imgUrl);
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

//    /**
//     * 反馈类型获取回调
//     *
//     * @param buttonView
//     * @param isChecked
//     */
//    @Override
//    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        if (isChecked) {
//            checkBoxString.add(buttonView.getText().toString());
//        } else {
//            String s = buttonView.getText().toString();
//            checkBoxString.remove(s);
//        }
//        String s = "";
//        sb = new StringBuilder();
//        for (int i = 0; i < checkBoxString.size(); i++) {
//            s = checkBoxString.get(i);
//            sb.append(s);
//        }
//        Log.d(TAG, "onCheckedChanged: sb == " + sb);
//    }

    public class MyRadioGroupOneListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (i == productPos.getId()) {              //商品问题
                if (productPos.isChecked()) {
                    type = 1;
                    typeItem2.clearCheck();
                }
            } else if (i == viewPos.getId()) {          //页面问题
                if (viewPos.isChecked()) {
                    type = 3;
                    typeItem2.clearCheck();
                }
            } else if (i == operatingPos.getId()) {     //操作问题
                if (operatingPos.isChecked()) {
                    type = 2;
                    typeItem2.clearCheck();
                }
            }
        }
    }

    public class MyRadioGroupTwoListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (i == errorPos.getId()) {                //闪退报错
                if (errorPos.isChecked()) {
                    type = 5;
                    typeItem1.clearCheck();
                }
            } else if (i == propose.getId()) {          //优化建议
                if (propose.isChecked()) {
                    type = 4;
                    typeItem1.clearCheck();
                }
            } else if (i == otherPos.getId()) {         //其他问题
                if (otherPos.isChecked()) {
                    type = 6;
                    typeItem1.clearCheck();
                }
            }
        }
    }
}
